<template>
	<div id="im">
		<div class="message-wrapper" ref="list">
			<ul>
				<li v-for="item in selectedChat" class="message-item">
					<template v-for="msg in item.messages">
						<div class="main" :class="{ self: msg.self }">
							<img class="avatar" width="36" height="36" :src="item.self ? item.user.avatar : item.user.avatar" />
							<div v-if="!msg.file" class="content" @click="tokenMgsDetail($event)">
								<div class="text" v-html="replaceFace(msg.content)"></div>
							</div>
							<div v-if="msg.file" @click="tokenMgsDetail($event)" data-file="true" v-html="replaceFace(msg.content)">

							</div>
						</div>
						<div class="time"><span>{{msg.date | time}}</span></div>
					</template>
				</li>
			</ul>
		</div>
		<div style="position: fixed;bottom:0px;left: 0px; right: 0px;">
			<van-field ref="text" v-model="content" @keypress="searchGoods" placeholder="请输入要咨询的问题" @click-right-icon="showAlert" right-icon="add-o" />
		</div>
		<van-popup v-model="show" closeable :overlay="true" position="bottom" :style="{ height: '40%' }">
			<van-tabs v-model="active" title-active-color="#318CF2" color="#318CF2" @click="tabClick">
			  <van-tab title="图标">
				  <div class="emojiBox">
				      <li v-for="(item, index) in emojis" class="emojis">
				         <img :src="require('../assets/emoji/'+item.file)" :data="item.code" @click="content +=item.code">
				      </li>
				  </div>
			  </van-tab>
			  <van-tab title="功能">
				  <div class="emojiBox">
					  <van-uploader :after-read="afterRead">
					    <van-button icon="photo-o" type="info"></van-button>
					  </van-uploader>
					  <span style="margin:10px"></span>
					  <van-uploader accept=".xls,.xlsx,doc,docx,.pdf" :after-read="afterFileRead">
					    <van-button icon="description" type="info"></van-button>
					  </van-uploader>
				  </div>
			  </van-tab>
			</van-tabs>
		</van-popup>
		<van-loading color="#1989fa" v-show="loading" style=" top: 50%;position: absolute;left: 50%;">
			图片上传中...
		</van-loading>
	</div>
</template>
<script>
	import { ImagePreview } from 'vant';
	export default {
		data() {
			return {
				content: '',
				show: false,
				active:'0',
				localUser:{},
				loading:false,
				selectedChat: [{
					id: 1,
					user: {
						name: '妈咪',
						avatar: require('../assets/images/mother.jpg')
					},
					messages: [{
							content: '么么哒，妈咪爱你', //聊天内容
							date: new Date() //时间
						},
						{
							content: '按回车可以发送信息，还可以给我发送表情哟',
							date: new Date()
						},
						{
							content: "test",
							date: new Date(),
							self: true
						}
					]
				}],
				emojis: [
				   { file: '100.gif', code: '/::)', title: '微笑',reg:/\/::\)/g },
				   { file: '101.gif', code: '/::~', title: '伤心',reg:/\/::~/g },
				   { file: '102.gif', code: '/::B', title: '美女',reg:/\/::B/g },
				   { file: '103.gif', code: '/::|', title: '发呆',reg:/\/::\|/g },
				   { file: '104.gif', code: '/:8-)', title: '墨镜',reg:/\/:8-\)/g },
				   { file: '105.gif', code: '/::<', title: '哭',reg:/\/::</g },
				   { file: '106.gif', code: '/::$', title: '羞',reg:/\/::\$/g },
				   { file: '107.gif', code: '/::X', title: '哑',reg:/\/::X/g },
				   { file: '108.gif', code: '/::Z', title: '睡',reg:/\/::Z/g },
				   { file: '109.gif', code: '/::\'(', title: '哭',reg:/\/::'\(/g },
				   { file: '110.gif', code: '/::-|', title: '囧',reg:/\/::-\|/g },
				   { file: '111.gif', code: '/::@', title: '怒',reg:/\/::@/g },
				   { file: '112.gif', code: '/::P', title: '调皮',reg:/\/::P/g },
				   { file: '113.gif', code: '/::D', title: '笑',reg:/\/::D/g },
				   { file: '114.gif', code: '/::O', title: '惊讶',reg:/\/::O/g },
				   { file: '115.gif', code: '/::(', title: '难过',reg:/\/::\(/g },
				   { file: '116.gif', code: '/::+', title: '酷',reg:/\/::\+/g },
				   { file: '117.gif', code: '/:--b', title: '汗',reg:/\/:--b/g },
				   { file: '118.gif', code: '/::Q', title: '抓狂',reg:/\/::Q/g },
				   { file: '119.gif', code: '/::T', title: '吐',reg:/\/::T/g },
				   { file: '120.gif', code: '/:,@P', title: '笑',reg:/\/:,@P/g },
				   { file: '121.gif', code: '/:,@-D', title: '快乐',reg:/\/:,@-D/g },
				   { file: '122.gif', code: '/::d', title: '奇',reg:/\/::d/g },
				   { file: '123.gif', code: '/:,@o', title: '傲' ,reg:/\/:,@o/g},
				   { file: '124.gif', code: '/::g', title: '饿',reg:/\/::g/g },
				   { file: '125.gif', code: '/:|-)', title: '累' ,reg:/\/:\|-\)/g},
				   { file: '126.gif', code: '/::!', title: '吓',reg:/\/::!/g },
				   { file: '127.gif', code: '/::L', title: '汗',reg:/\/::L/g },
				   { file: '128.gif', code: '/::>', title: '高兴',reg:/\/::>/g },
				   { file: '129.gif', code: '/::,@', title: '闲',reg:/\/::,@/g },
				   { file: '130.gif', code: '/:,@f', title: '努力',reg:/\/:,@f/g },
				   { file: '131.gif', code: '/::-S', title: '骂',reg:/\/::-S/g },
				   { file: '133.gif', code: '/:,@x', title: '秘密',reg:/\/:,@x/g },
				   { file: '134.gif', code: '/:,@@', title: '乱',reg:/\/:,@@/g },
				   { file: '135.gif', code: '/::8', title: '疯',reg:/\/::8/g },
				   { file: '136.gif', code: '/:,@!', title: '哀',reg:/\/:,@!/g },
				   { file: '137.gif', code: '/:!!!', title: '鬼',reg:/\/:!!!/g },
				   { file: '138.gif', code: '/:xx', title: '打击',reg:/\/:xx/g },
				   { file: '139.gif', code: '/:bye', title: 'bye',reg:/\/:bye/g },
				   { file: '142.gif', code: '/:handclap', title: '鼓掌',reg:/\/:handclap/g },
				   { file: '145.gif', code: '/:<@', title: '什么',reg:/\/:<@/g },
				   { file: '147.gif', code: '/::-O', title: '累',reg:/\/::-O/g },
				   { file: '153.gif', code: '/:@x', title: '吓',reg:/\/:@x/g },
				   { file: '155.gif', code: '/:pd', title: '刀',reg:/\/:pd/g },
				   { file: '156.gif', code: '/:<W>', title: '水果',reg:/\/:<W>/g },
				   { file: '157.gif', code: '/:beer', title: '酒',reg:/\/:beer/g },
				   { file: '158.gif', code: '/:basketb', title: '篮球',reg:/\/:basketb/g },
				   { file: '159.gif', code: '/:oo', title: '乒乓',reg:/\/:oo/g },
				   { file: '195.gif', code: '/:circle', title: '跳舞',reg:/\/:circle/g },
				   { file: '160.gif', code: '/:coffee', title: '咖啡',reg:/\/:coffee/g }
				],
			}
		},
		components: {

		},
		created() {
			this.initWebSocket();
			if(localStorage.getItem("msgmobile")){
			   this.selectedChat = JSON.parse(localStorage.getItem("msgmobile"));
			}
		},
		filters: {
		  // 将日期过滤为 hour:minutes
		  time(date) {
		    if (typeof date === 'string') {
		      date = new Date(date);
		    }
		    var month = date.getMonth() + 1;
		    var day = date.getDate();
		    if (date.getMinutes() < 10) {
		      return month + "-" + day + " " + date.getHours() + ':0' + date.getMinutes();
		    } else {
		      return month + "-" + day + " " + date.getHours() + ':' + date.getMinutes();
		    }
		  }
		},
		watch: {
		  // 发送信息后,让信息滚动到最下面
		  selectedChat() {
		    if(this.$refs.list){
		      setTimeout(() => this.$refs.list.scrollTop = this.$refs.list.scrollHeight, 0)
		    }
		  }
		},
		methods: {
			tokenMgsDetail(e){
			  var isFile = e.target.getAttribute("class");
			  if(e.target.nodeName === 'IMG' && isFile !== "file"){
			     ImagePreview([
			       e.target.src
			     ]);
			  }
			},
			afterFileRead(file){
				this.loading = true;
				var f = file.file;
				let size = Math.floor(f.size / 1024);	
		　　　　 let formData = new FormData();
		　　　　 formData.append('file', file.file);
				console.log(formData);
				console.log(formData.get('file'));
				this.$http.post('http://localhost:8889/common/upload',formData,{
					headers:{
				　　　　　　'Content-Type':'multipart/form-data' //值得注意的是，这个地方一定要把请求头更改一下
				　　　　 }
				}).then(function(res){
				　　console.log(res,"此处应该是请求成功的回调")　　
					var html  =  '';
					var size = parseFloat(f.size/1024).toFixed(1) + 'KB';
					
					if(f.type === "application/pdf"){
					  var image = require("../assets/pdf_white.png");
					  html ='<a href="'+res.body.url+'" ><div class="fileCard"><img src="'+image+'"  class="file" alt="" style="float:right;vertical-align: middle; width: auto; cursor: pointer; height: 50px" /><div class="fileCardName">'+f.name+'</div><div style="font-size: 10px; margin-top: 12px;text-align: left;">'+size+'</div></div></a>';
					}
					if(file.type === "application/vnd.ms-excel" || file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){
					  var image = require("../assets/excel_white.png");
					  html =  '<a href="'+res.body.url+'" ><div class="fileCard"><img src="'+image+'"  alt="" class="file" style="float:right;vertical-align: middle; width: auto; cursor: pointer; height: 50px" /><div class="fileCardName">'+f.name+'</div><div style="font-size: 10px; margin-top: 12px;text-align: left;">'+size+'</div></div></a>';
					}
					if(file.type === "application/msword" || file.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document"){
					  var image = require("../assets/word_white.png");
					  html =  '<a href="'+res.body.url+'" ><div class="fileCard"><img src="'+image+'"  alt="" class="file" style="float:right;vertical-align: middle; width: auto; cursor: pointer; height: 50px" /><div class="fileCardName">'+f.name+'</div><div style="font-size: 10px; margin-top: 12px;text-align: left;">'+size+'</div></div></a>';
					}
					this.selectedChat.push({
						id: 1,
						user: this.localUser,
						messages: [ {
							content: html,
							date: new Date(),
							self: true
						  }
						]
					});
					localStorage.setItem('msgmobile',JSON.stringify(this.selectedChat));
					var createTime = new Date().getTime();
					var msg = "{\"from\": \""+this.localUser.userId+"\",\"to\": \""+this.localUser.friends[0].users[0].userId  +"\",\"cmd\":11,\"createTime\":"+createTime+",\"chatType\":\"2\",\"msgType\": \"0\",\"content\": '"+html+"'}";
					this.websocketsend(msg);
					this.show = false;
					this.loading = false;
		　　　　 }).catch(function(req){
		　　　　　　 console.log(req,"请求失败的回调，自己看看为啥失败");
					this.loading = false;
		　　　　 });
			},
			afterRead(file){
				this.loading = true;
				var f = file.file;
				let size = Math.floor(f.size / 1024);	
				let formData = new FormData();
				formData.append('file', file.file);
				console.log(formData);
				console.log(formData.get('file'));
				this.$http.post('http://localhost:8889/common/upload',formData,{
					headers:{
				　　　　　　'Content-Type':'multipart/form-data' //值得注意的是，这个地方一定要把请求头更改一下
				　　　　 }
				}).then(function(res){
				　　console.log(res,"此处应该是请求成功的回调")　　
					var html  =  '<img src="' + res.body.url +'"  alt="" style="vertical-align: middle; width: auto; cursor: pointer; height: 100px" />';
					this.selectedChat.push({
						id: 1,
						user: this.localUser,
						messages: [ {
							content: html,
							date: new Date(),
							self: true
						  }
						]
					});
					localStorage.setItem('msgmobile',JSON.stringify(this.selectedChat));
					var createTime = new Date().getTime();
					var msg = "{\"from\": \""+this.localUser.userId+"\",\"to\": \""+this.localUser.friends[0].users[0].userId  +"\",\"cmd\":11,\"createTime\":"+createTime+",\"chatType\":\"2\",\"msgType\": \"0\",\"content\": '"+html+"'}";
					this.websocketsend(msg);
					this.show = false;
					this.loading = false;
		　　　　 }).catch(function(req){
		　　　　　　 console.log(req,"请求失败的回调，自己看看为啥失败");
					this.loading = false;
		　　　　 });
			},
			searchGoods(event){
				if (event.keyCode == 13) { //如果按的是enter键 13是enter 
					event.preventDefault(); //禁止默认事件（默认是换行） 
					this.send();
				 }
			},
			initWebSocket(){
			  const wsuri = "ws://127.0.0.1:9000?username=girl&password=96e79218965eb72c92a549dd5a330112";
			  this.websock = new WebSocket(wsuri);
			  this.websock.onmessage = this.websocketonmessage;
			  this.websock.onopen = this.websocketonopen;
			  this.websock.onerror = this.websocketonerror;
			  this.websock.onclose = this.websocketclose;
			},
			websocketonopen(){
			  // 连接启动心跳
			  //this.start();
			  const allUser = "{'cmd': 17,'userid': '10','type' :'3'}";
			  this.websocketsend(allUser);
			},
			websocketonerror(){
			  //连接建立失败重连
			  this.reconnect();
			},
			websocketonmessage(e){
			  //数据接收
			  const dataObj = JSON.parse(e.data);
			  var that = this;
			  console.log(dataObj);
			  if(dataObj.command == 6){
			    this.status = "连接成功"
			  }else if(dataObj.command == 9){//加入群组的消息通知处理;
			    //that.COMMAND_JOIN_GROUP_NOTIFY_RESP(dataObj);
			  }else if(dataObj.command == 6){
			    this.status = "连接不成功"
			  }else if(dataObj.command == 11){
			    this.getMessageLocation(dataObj.data.content);
			  }else if(dataObj.command == 0){
			    if(dataObj.code === 20000){
			       this.localUser = dataObj.data;
			    }
			    if(dataObj.code === 20001){
			      for(var i = 0;i<dataObj.data.length;i++){
			        this.selectedChat.push({
			            id: 1,
			            user: this.localUser.friends[0].users[0],
			            messages: [ {
			                content: dataObj.data[i].content,
			                date: new Date(dataObj.data[i].createTime)
			              }
			            ]
			        });
			      }
			    }
			  }
			  //this.reset();
			},
			websocketsend(Data){
			  //数据发送
			  this.websock.send(Data);
			},
			websocketclose(e){
			  // 关闭，不需要连接
			  console.log('断开连接',e);
			  this.isOpen = false;
			  this.status = "连接不成功"
			},
			// 按回车发送信息
			onKeyup (e) {
			    if ( event.ctrlKey && event.keyCode == 13 ) {
			       this.send()
			    }
			},
			
			// 点击发送按钮发送信息
			send () {
				var msg = this.content;
				this.selectedChat.push({
				    id: 1,
				    user: this.localUser,
				    messages: [ {
				        content: msg,
				        date: new Date(),
				        self: true
				      }
				    ]
				});
				localStorage.setItem('msgmobile',JSON.stringify(this.selectedChat));
				var createTime = new Date().getTime();
				var msg = "{\"from\": \""+this.localUser.userId+"\",\"to\": \""+this.localUser.friends[0].users[0].userId  +"\",\"cmd\":11,\"createTime\":"+createTime+",\"chatType\":\"2\",\"msgType\": \"0\",\"content\": '"+msg+"'}";
				this.websocketsend(msg);
				this.content = '';
			},
			getMessageLocation(msg){
			  this.selectedChat.push({
			      id: 1,
			      user: this.localUser.friends[0].users[0],
			      messages: [ {
			          content: msg,
			          date: new Date(),
			        }
			      ]
			  });
			  localStorage.setItem('msgmobile',JSON.stringify(this.selectedChat));
			},
			tabClick(e){
				console.log(e);
			},
			showAlert() {
				this.show = true;
			},
			//  经过v-html 渲染成真正的图片
			replaceFace(con) {
			  if (con.includes('/:')) {
			    var emojis = this.emojis;
			    for (var i = 0; i < emojis.length; i++) {
				  var img = require('../assets/emoji/'+emojis[i].file);
			      con = con.replace(emojis[i].reg, '<img src="'+ img +
			        '"  alt="" style="vertical-align: middle; width: 24px; height: 24px" />');
			    }
			    return con;
			  }
			  return con;
			},
		}
	}
</script>

<style lang="stylus">
	.fileCard {
	  width: 170px;
	  border: 1px solid #318cf2;
	  height: 70px;
	  padding: 10px;
	  border-radius: 5px;
	  background: #318cf2;
	  color: white;
	  display: inline-block;
	  position: relative;
	  cursor: pointer;
	  line-height: 20px;
	}
	.fileCard:before {
	    position: absolute;
	    top: 12px;
	    content :' ';
	    border: 6px solid transparent;
	    right: -12px;
	    display: inline-block;
	    vertical-align: middle;
	    border-right-color: transparent;
	    border-left-color: #318CF2;
	}
	.fileCardName {
	  font-size: 13px;
	  display: -webkit-box;
	  word-break: break-all;
	  text-overflow: ellipsis;
	  overflow: hidden;
	  white-space: pre-line;
	  -webkit-box-orient: vertical;
	  -webkit-line-clamp: 2;
	  text-align: left;
	}
	.message-wrapper {
	  height: calc(100vh - 44px); 
	  width:100%;
	  padding: 10px;
	  box-sizing: border-box;
	  overflow-y: auto;
	  border-bottom: 1px solid #e7e7e7;
	}
	
	.message-wrapper .message {
	  margin-bottom: 15px;
	}
	
	.message-wrapper .time {
	  width: 100%;
	  font-size: 12px;
	  margin: 7px auto;
	  text-align: center;
	}
	
	.message-wrapper .time span {
	  display: inline-block;
	  padding: 4px 6px;
	  color: #fff;
	  border-radius: 3px;
	  background-color: #dcdcdc;
	}
	#im .emojiBox{
		padding: 10px;
	}
	#im .emojis {
		list-style: none;
		position: relative;
		display: inline-block;
		width: 55px;
		height: 40px;
		line-height: 40px;
		font-size: 12px;
		padding: 0 20px;
		box-sizing: border-box;
		color: #7c7c7c;
	}
	#im .van-cell {
		background: #fafafa;
	}
	#im .main
	  .avatar
	      float: left
	      margin-left: 10px
	      border-radius: 3px
	  .content
	      display: inline-block
	      margin-left: 10px
	      position: relative
	      padding: 6px 10px
	      max-width: 330px
	      min-height: 36px
	      line-height: 24px
	      box-sizing: border-box
	      font-size: 13px
	      text-align: left
	      word-break: break-all
	      background-color: #fafafa
	      border-radius: 4px
	      .text
	          white-space: pre-line
	      &:before
	          content: " "
	          position: absolute
	          top: 12px
	          right: 100%
	          border: 6px solid transparent
	          border-right-color: #fafafa
	#im .self
	    text-align: right
	    .avatar
	        float: right
	        margin:0 10px
	    .content
	        background-color: #318CF2
	        color:white
	        &:before
	            right: -12px
	            vertical-align: middle
	            border-right-color: transparent
	            border-left-color: #318CF2
</style>
